package cn.ytr.crm.service.impl;

import cn.ytr.crm.domain.Role;
import cn.ytr.crm.mapper.RoleMapper;
import cn.ytr.crm.query.PageResult;
import cn.ytr.crm.query.QueryObject;
import cn.ytr.crm.service.IRoleService;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class RoleServiceImpl implements IRoleService{

	@Autowired
	private RoleMapper roleMapper;
	@Autowired
	private EhCacheManager ehCacheManager;

	/**
	 * 新增或编辑角色
	 */
	@Override
	public void saveOrUpate(Role role, Long[] permissionIds) {
		// 判断是否编辑
		if (role.getId() != null) {
			roleMapper.updateByPrimaryKey(role);
			//编辑角色的话要把原中间表对应的先删掉，后面再增加关系记录
			roleMapper.deleteRelation(role.getId());

            //清空所有人的缓存
            ehCacheManager.getCacheManager().clearAll();
		} else {
			roleMapper.insert(role);
		}

		//维护 角色权限中间表 增加记录
		if (permissionIds != null && permissionIds.length > 0) {
			for (Long permissionId : permissionIds) {
				roleMapper.insertRelation(role.getId(), permissionId);
			}
		}
	}

	/**
	 * 删除某角色
	 */
	@Override
	public void delete(Long id) {
		roleMapper.deleteByPrimaryKey(id);
		//维护 角色权限中间表 删除某角色的话也要把中间表对应的删掉
		roleMapper.deleteRelation(id);
	}

	/**
	 * 获取某角色
	 */
	@Override
	@Transactional(readOnly=true)
	public Role get(Long id) {
		Role role = roleMapper.selectByPrimaryKey(id);
		return role;
	}

	/**
	 * 获取所有角色
	 */
	@Override
	@Transactional(readOnly=true)
	public List<Role> listAll() {
		List<Role> list = roleMapper.selectAll();
		return list;
	}

	/**
	 * 高级查询所有角色
	 */
	@Override
	@Transactional(readOnly=true)
	public PageResult query(QueryObject qo) {
		Integer count = roleMapper.selectForCount(qo);
		if (count < 1 || count == null) {
			return new PageResult(qo.getPageSize());
		} else {
			List<Role> list = roleMapper.selectForList(qo);
			return new PageResult(qo.getCurrentPage(), count, list, qo.getPageSize());
		}
	}

}
